package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    //营业额统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.准备日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        log.info("dateList:{}", dateList);

        //2.查orders表（根据begin和end）
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//用于处理没有营业额的情况
            turnoverList.add(turnover);
        });
        log.info("turnoverList:{}", turnoverList);
        //3.构造TurnoverReportVO对象
        /*TurnoverReportVO result = new TurnoverReportVO();
        result.setDateList(StringUtils.join(dateList,","));
        result.setTurnoverList(turnoverList.toString());*/
        /*result.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(turnoverList.toString())
                .build();
*/

        return TurnoverReportVO.builder()
                .turnoverList(turnoverList.toString())
                .dateList(StringUtils.join(dateList, ","))
                .build();
    }

    //用户统计
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.构造dateList
        List<LocalDate> dateList = getDateList(begin, end);
        log.info("dateList:{}", dateList);
        //2.构造newUserList
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer count = userMapper.countByMap(map);
            newUserList.add(count);
            //3.构造totalUserList
            map.put("beginTime", null);
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });


        //4.封装UserReportVO
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    //订单统计
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        //1.构造dateList
        List<LocalDate> dateList = getDateList(begin, end);
        //2.构造每日总订单列表数orderCountList
        //select count(*) from orders where create_time between #{} and #{}
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer totalValidOrderCount = 0;
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer orderSum = ordersMapper.countByMap(map);
            orderCountList.add(orderSum);
            //3.获取每日有效订单validOrderCountList
            map.put("status", Orders.COMPLETED);
            Integer orderValidSum = ordersMapper.countByMap(map);
            validOrderCountList.add(orderValidSum);
            //4.获取订单总数totalOrderList
            totalOrderCount=totalOrderCount+orderSum;
            //5.获取有效订单数validOrderLis
            totalValidOrderCount=totalValidOrderCount+orderValidSum;
        }
        //6.计算完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate= (totalValidOrderCount+0.0)/totalOrderCount;
        }
        //7.封装OrderReportVO对象
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    //前十菜品
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.构造nameList商品名称列表
        Map map = new HashMap();
        map.put("status",Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        List<Map> list= ordersMapper.sumTop10(map);
        List<Object> nameList = new ArrayList<>();
        List<Object> numberList = new ArrayList<>();
        for (Map m : list) {
            Object name =  m.get("name");
            nameList.add(name);
            //2.构造numberList商品销量列表
            Object number =  m.get("total_number");
            numberList.add(number);
        }
        log.info("nameList:{}", nameList);
        //3.封装SalesTop10ReportVO
        SalesTop10ReportVO result = new SalesTop10ReportVO();
        result.setNameList(StringUtils.join(nameList, ","));
        result.setNumberList(StringUtils.join(numberList, ","));
        return result;
       /* return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();*/
    }
    //导出运营数据报表
    @Override
    public void exportBusinesData(HttpServletResponse response) throws IOException {
        //1.查数据库获取营业数据--最近30天的数据
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = end.minusDays(30);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData
                (LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2.通过poi将数据写入excel文件中
        FileInputStream fileInputStream = new FileInputStream("D:\\Tools\\IntelliJ IDEA 2024.3.4.1\\studay\\Java147-prj\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet1 = workbook.getSheet("Sheet1");
        //填充数据---时间
        sheet1.getRow(1).getCell(1).setCellValue("时间："+begin+"-"+end);
        //获取第四行并填充数据
        XSSFRow row4 = sheet1.getRow(3);
        row4.getCell(2).setCellValue(businessDataVO.getTurnover());
        row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
        //获取第五行并填充数据
        XSSFRow row5 = sheet1.getRow(4);
        row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //查某一天的营业数据
            BusinessDataVO businessData = workspaceService.getBusinessData
                    (LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
        }

        //3.通过输出流将excel文件下载到客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
        fileInputStream.close();
    }

    /*
     * 获取日期列表数据
     * */
    private static List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<LocalDate>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
